package com.campus.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.Map;

public class JwtUtil {
    private static final String JWT_SECRET = "jwt_secret_1234567890_sangeng_security_key";
    private static final long TOKEN_EXPIRE = 1000 * 60 * 60 * 3;//3小时

    /**
     * 生成安全密钥
     */
    private static SecretKey getSecretKey() {
        return Keys.hmacShaKeyFor(JWT_SECRET.getBytes());
    }

    public static String createJwt(Map<String, Object> data) {
        return Jwts.builder()
                .setClaims(data)  // 先设置claims
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRE))
                .signWith(getSecretKey(), SignatureAlgorithm.HS256)  // 最后签名
                .compact();
    }

    public static Claims parseJwt(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSecretKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}
